<template>
  <page-meta :root-font-size="globalData.fontsize + 'px'" user-scalable="no" viewport-fit="cover" style="display: block"></page-meta>
  <view class="procurement">
    <view :style="globalData.appStyle.customizeBarStyle">
      <uni-nav-bar :height="globalData.navBarInfo.height" backgroundColor="#FF7C00" :border="false">
        <block slot="left">
          <view @click="jumpToPage('/pages/sale/add/index?pushType=2')" class="leftLabel cWH">发布销售</view>
        </block>
        <view class="inputView flca" @click="jumpToPageWithEvent('/pages/global/search-page/common-search/index?searchMode=2', 1)">
          <uni-icons type="search" size="21"></uni-icons>
          <input confirm-type="search" type="text" class="input" placeholder="请输入搜索内容" />
        </view>
      </uni-nav-bar>
    </view>
    <view class="crad_box w100p" :style="globalData.appStyle.customizeContentStyle">
      <scroll-view scroll-y :style="'height:' + (secondParams.pageNum > 1 ? globalData.customizeInfo.customizeContentHeight - 54 : globalData.customizeInfo.customizeContentHeight) + 'rem;overflow: auto;'" @scrolltoupper="scrolltoupper" @scrolltolower="scrolltolower" @scroll="scroll" :scroll-top="scrollTop">
        <view>
          <view class="icon_box w100p">
            <view v-for="item in categoryList" :key="item.categoryName" class="icon_view flc" @click="setCategoryForSearch(item)">
              <image class="icons" :src="`../static/img/procurement/${name2Png(item.categoryName)}.png`" mode="scaleToFill" />
              <view class="text">{{ item.categoryName }}</view>
            </view>
          </view>
          <!-- 未来关注的提示样式 -->
          <Gongzhonghao v-if="globalData.userInfo.isFollowOfficialAccount !== '1'" />
          <!-- 筛选模块的样式 -->
          <view class="winnow_box">
            <view class="flr winnow_top_small">
              <view class="winnow_tag">
                <text :class="firstParams.orderBy === '' ? 'winnow_tag_active' : ''" @click="setSortType('')">全部</text>
                <text :class="firstParams.orderBy === 'createTime' ? 'winnow_tag_active' : ''" @click="setSortType('createTime')">最新</text>
                <text :class="firstParams.orderBy === 'score' ? 'winnow_tag_active' : ''" @click="setSortType('score')">好评</text>
              </view>
              <!-- <view class="winnow_middle flex1"> 差评全额退积分 </view> -->
              <view class="notice_content flex1">
                <uni-notice-bar showIcon color="rgba(255, 118, 17, 1)" background-color="rgba(255, 251, 247, 1)" :scrollable="true" single :text="globalData.noticeInfoNext"></uni-notice-bar>
              </view>
              <view class="winnow_left" @click="jumpToPageWithEvent(`/pages/global/categorySelection/index?searchMode=1&newSource=${firstParams.categoryList.length ? 1 : 0}`, 2)">
                <image class="winnow_right_icon" src="../static/img/global/winnowIcon.png"></image>
                <text class="winnow_right_txt">筛选{{ firstParams.categoryList.length ? `·${firstParams.categoryList.length}项` : '' }}</text>
              </view>
            </view>
            <view class="notice_content">
              <uni-notice-bar showIcon color="rgba(255, 118, 17, 1)" background-color="rgba(255, 251, 247, 1)" :scrollable="true" single :text="globalData.noticeInfo"></uni-notice-bar>
            </view>
          </view>
          <view class="crad_loop_box" v-for="(item, key) in scrollViewData" :key="key" @click="cardItemClick(item)">
            <view v-if="item && item.hasOwnProperty('contactPhoneNumber')" class="white_bg_box">
              <view v-if="item.isTopping == 1" class="zd">置顶</view>
              <view class="ell2 card_title line-clamp-2">
                <text>{{ item.title ? item.title : item.detailInfo }}</text>
              </view>
              <view class="card_content frt">
                <view class="flr flw flex1">
                  <view v-for="(label, key) in item.labels.split(',').filter(el => el) || []" :key="key" :class="key < 2 ? 'small_orange_bg_tag' : 'small_gray_bg_tag'">
                    {{ label }}
                  </view>
                </view>
                <view style="margin-right: 14rem" class="flcv">
                  <img src="/static/img/procurement/addLike.png" class="small_icons_addLike" />
                  <text>{{ item.awardQty }}</text>
                </view>
                <view class="flcv">
                  <img src="/static/img/procurement/watched.png" class="small_icons_watched" />
                  <text>{{ item.checkQty }}</text>
                </view>
              </view>
              <view class="flcv mt15">
                <uni-icons type="location" style="margin-right: 6rem" size="15"></uni-icons>
                <text class="flex1 address_txt">{{ item.deliveryAddress }}</text>
                <view class="flcv">
                  <view><uni-rate size="12" :readonly="true" v-model="item.score" /></view>
                  <text class="normal_twelve_txt orange_color">{{ item.score ? item.score : 0.0 }}</text>
                  <text class="normal_twelve_txt">分</text>
                  <text class="normal_twelve_txt ml12 small_gary_twelve_txt">{{ formatDateTime(item.createTime, 'zh') }}</text>
                  <view v-if="globalData.userInfo.id !== item.publishUserId" class="call_phone flca" @click.stop="callPhone(item)">
                    <uni-icons type="phone" color="#ff7000" size="16"></uni-icons>
                    <text>拨打电话</text>
                  </view>
                </view>
              </view>
            </view>
            <view v-else class="crad_loop_box" style="padding: 0 !important">
              <image class="advertise-box" mode="scaleToFill" :src="item.pic" />
            </view>
          </view>
        </view>
        <view v-if="secondParams.pageNum > 1" class="back_to_top" @click="backToTop()">
          <uni-icons type="pulldown" size="29"></uni-icons>
        </view>
      </scroll-view>
      <view class="suspend_box flca">
        <view class="flr">
          <view class="left_radius flca" @click="jumpToPage('/pages/procurement/add/index?pushType=2')">
            <image class="small_solid_arrow" src="../static/img/procurement/leftSolidArrow.png"></image>
            发布采购信息
          </view>
          <view class="right_radius flca" @click="jumpToPage('/pages/sale/add/index?pushType=2')">
            发布销售信息
            <image class="small_solid_arrow" src="../static/img/procurement/rightSolidArrow.png"></image>
          </view>
        </view>
      </view>
    </view>
    <!-- <view @click="openEvaluated">打开评价弹窗</view> -->
    <uni-popup ref="popup" type="bottom" class="evaluated-popup" :is-mask-click="false" background-color="#fff" border-radius="20rem 20rem 0 0">
      <to-be-evaluated :targetIdInfo="targetIdInfo" :showType="2" @closePopup="closePopup" />
    </uni-popup>
    <call-tips ref="callTips" @openEvaluated="openEvaluated" />
  </view>
</template>
<script>
const api = require('@/utils/request.js');
import commonMxins from '@/mixins/common.js';
import ToBeEvaluated from '@/component/ToBeEvaluated.vue';
import CallTips from '@/component/call-phone-tips/index.vue';
import Gongzhonghao from '@/component/Gongzhonghao.vue';
export default {
  components: { Gongzhonghao, ToBeEvaluated, CallTips },
  mixins: [commonMxins],
  data() {
    return {
      targetIdInfo: { targetId: '', startTime: '', releaseTime: '' },
      firstParams: {
        keywords: '',
        orderBy: '',
        categoryList: []
      },
      secondParams: {
        pageSize: 20,
        pageNum: 1
      },
      advertiseParams: {
        pageSize: 4,
        pageNum: 1,
        location: '3'
      },
      firstTableData: [],
      secondTableData: [],
      firstAdvertisementList: [], //广告列表
      secondAdvertisementList: [], //广告列表
      scrollViewData: [],
      categoryList: [], //类目列表
      value: 2,
      selectValue: 1,
      nameToPng: {
        机械设备: 'jxjhysb',
        五金工具: 'wjgj',
        服装: 'fz',
        '服饰、鞋帽': 'fs_xm',
        化工: 'hg',
        精细化学品: 'jxhxp',
        橡塑: 'xs',
        商务服务: 'swfw',
        印刷: 'ys',
        纸业: 'zy',
        '医药、保养': 'yy_by',
        汽摩及配件: 'qmjpj',
        家用电器: 'jydq',
        '安全、防护': 'aq_fh',
        能源: 'ny',
        交通运输: 'jtys',
        库存积压: 'kcjy',
        照明: 'zm',
        '仪器、仪表': 'yq_yb',
        电子元器件: 'dzyqj',
        电工电气: 'dgdq',
        '数码、电脑': 'sm_dn',
        '运动、休闲': 'yd_xx',
        建筑建材: 'jzcl',
        家居用品: 'jjyp',
        '纺织、皮革': 'fz_pg',
        包装: 'bz',
        '办公、文教': 'bg_wj',
        '食品、饮料': 'sp_yl',
        农业: 'ny1',
        冶金矿产: 'yjkc',
        '礼品、工艺品、饰品': 'lp_gyp_sp',
        学习视频: 'xx_sp',
        联系记录: 'lx_jl'
      },
      scrollTop: 0,
      old: {
        scrollTop: 0
      }
    };
  },
  onShow() {
    const categoryName = uni.getStorageSync('categoryName') ? uni.getStorageSync('categoryName') : null;
    categoryName && (this.firstParams.categoryList = [categoryName]);
    uni.removeStorageSync('categoryName');
  },
  async onLoad(options) {
    this.setKeyWordsForSearch(options?.keywords ?? ''); // 用户输入关键词并搜索
    await this.appInit();
    this.searchData();
    this.getHotCategory(); // 获取热门分类
    // TODO 评价查接口
    this.showToBeEvaluated();
  },
  methods: {
    onShareAppMessage(res) {
      return { title: 'E商机-商机触手可得', path: `/pages/salePage?shareId=${this.globalData.userInfo.id}` };
    },
    onShareTimeline(res) {
      return { title: 'E商机-商机触手可得', path: '/pages/salePage' };
    },
    backToTop() {
      this.scrollTop = this.old.scrollTop;
      this.$nextTick(function () {
        this.scrollTop = 0;
      });
    },
    scroll(e) {
      this.old.scrollTop = e.detail.scrollTop;
    },
    // 上下滑动数据加载
    scrolltoupper() {
      this.searchData();
    },
    scrolltolower() {
      this.secondParams.pageNum += 1;
      this.searchSecondTableData();
    },
    // 前置-未评价通话进行处理
    showToBeEvaluated() {
      const commentInfo = this.globalData.MyUncommentContactObj ? [this.globalData.MyUncommentContactObj].find(el => el.demandType == 2) : false;
      if (commentInfo) {
        const { demandId, startTime, releaseTime, historyContactRecordId } = commentInfo;
        this.openEvaluated({ targetId: String(demandId), startTime, releaseTime, historyContactRecordId });
      }
    },
    // 关闭评价弹窗
    closePopup() {
      this.$refs.popup.close();
    },
    // 打开评价弹窗
    openEvaluated(targetIdInfo) {
      this.targetIdInfo = targetIdInfo;
      this.$refs.popup.open('bottom');
    },
    //点击跳转详情
    async cardItemClick(item) {
      // 做数据处理-广告还是详情
      if (item.contactPhoneNumber) {
        api
          .request({ url: '/saleInfo/check', data: { saleInfoId: item.id }, method: 'POST' })
          .then(result => {
            uni.navigateTo({ url: `/pages/sale/detail/index?saleInfoId=${item.id}` });
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        await this.openAdvertiseCheck(item.id);
        if (item.demandId) {
          uni.navigateTo({ url: `/pages/sale/detail/index?saleInfoId=${item.demandId}` });
        } else {
          uni.navigateTo({ url: '/pages/global/webview?src=' + encodeURIComponent(item.url) });
        }
      }
    },
    // 点击广告调用check接口
    async openAdvertiseCheck(advertisementId) {
      await api.request({ url: '/advertisement/check', data: { advertisementId }, method: 'GET' });
    },
    name2Png(name) {
      return this.nameToPng[name];
    },
    // 获取最热类型
    async getHotCategory() {
      let res = await api.request({ url: '/category/queryHotCategory', data: {}, method: 'GET' });
      this.categoryList = res.data.concat([{ categoryName: '学习视频' }, { categoryName: '联系记录' }]);
    },
    async callPhone(item) {
      if (!this.globalData.userInfo.phoneNumber) {
        uni.navigateTo({ url: '/pages/global/authorizePhone' });
      } else {
        this.$refs.callTips.open(String(item.id), 2);
      }
    },
    // 设置排序检索条件
    async setSortType(orderBy) {
      if (orderBy === '') {
        this.firstParams = {
          keywords: '',
          orderBy,
          categoryList: []
        };
      } else {
        this.firstParams.orderBy = orderBy;
      }
      this.searchData();
    },
    // 设置分类检索条件
    setCategoryForSearch(category) {
      switch (category.categoryName) {
        case '学习视频':
          uni.switchTab({ url: '/pages/video/index' });
          break;
        case '联系记录':
          uni.navigateTo({ url: '/pages/my/contactList/index' });
          break;
        default:
          this.firstParams.categoryList = [category.categoryName];
          this.searchData();
          break;
      }
    },
    // 根据搜索内容检索
    setKeyWordsForSearch(keywords) {
      this.firstParams.keywords = keywords;
    },
    resetSearchParams() {
      this.firstParams = {
        keywords: '',
        orderBy: '',
        categoryList: [] // saleCategory销售
      };
      this.secondParams.pageNum = 1;
      this.scrollViewData = [];
    },
    /**
     * 根据需求调整内容
     * 1、先根据第一个接口获取前20条数据，每五条，添加一条广告
     * 2、再根据第二个接口获取余下的其他数据，每五条，添加一条广告
     * 3、需要考虑上拉刷新和下拉刷新问题
     */
    // 汇总接口，调用第一和第二个接口
    async searchData() {
      await this.searchFirstTableData();
      await this.searchSecondTableData();
    },
    // 检索内容
    // 传入参数控制scrollViewData为空白问题处理
    async searchFirstTableData() {
      const res = await api.request({ url: '/saleInfo/selectPageSaleInfoFirst', data: { ...this.firstParams }, method: 'POST' });
      await this.getAdvertisementList('first', 1); // 查询广告
      if (res.data && res.data.length > 0) {
        this.firstTableData = res.data;
      }
      // 做广告插入处理
      let showData = [];
      if (this.firstAdvertisementList.length) {
        res.data.forEach((element, index) => {
          showData.push(element);
          if (index % 5 === 4) {
            showData.push(this.firstAdvertisementList.pop());
          }
        });
      } else {
        showData = this.firstTableData;
      }
      this.scrollViewData = showData;
    },
    async searchSecondTableData() {
      const res = await api.request({ url: '/saleInfo/selectPageSaleInfoSecond', data: { ...this.secondParams }, method: 'POST' });
      await this.getAdvertisementList('second', this.secondParams.pageNum + 1); // 查询广告
      if (res.data && res.data.length > 0) {
        this.secondTableData = res.data;
      }
      // 做广告插入处理
      let showData = [];
      if (this.secondAdvertisementList.length) {
        res.data.forEach((element, index) => {
          showData.push(element);
          if (index % 5 === 4) {
            showData.push(this.secondAdvertisementList.pop());
          }
        });
      } else {
        showData = this.secondTableData;
      }
      this.scrollViewData = this.scrollViewData.concat(showData);
    },
    // 查询广告的接口
    async getAdvertisementList(resType, pageNum) {
      const res = await api.request({ url: '/advertisement/selectPageAdvertisement', data: { ...this.advertiseParams, pageNum }, method: 'GET' });
      if (res.data && res.data.length > 0) {
        if (resType === 'first') {
          this.firstAdvertisementList = res.data.reverse() || [];
        } else {
          this.secondAdvertisementList = res.data.reverse() || [];
        }
      }
    },
    upper: function (e) {
      console.log(e);
    },
    lower: function (e) {
      console.log(e);
    },
    scroll: function (e) {
      console.log(e);
      this.old.scrollTop = e.detail.scrollTop;
    },
    goTop: function (e) {
      // 解决view层不同步的问题
      this.scrollTop = this.old.scrollTop;
      this.$nextTick(function () {
        this.scrollTop = 0;
      });
      // uni.showToast({
      //   icon: 'none',
      //   title: '纵向滚动 scrollTop 值已被修改为 0'
      // });
    },
    jumpToPage(url) {
      if (!this.globalData.userInfo.phoneNumber) {
        uni.navigateTo({ url: '/pages/global/authorizePhone' });
      } else {
        uni.navigateTo({ url });
      }
    },
    jumpToPageWithEvent(url, type) {
      // 检索页面
      if (type === 1) {
        uni.navigateTo({
          url,
          events: {
            searchInfo: keywords => {
              this.params.keywords = keywords;
              this.searchData();
            }
          }
        });
      } else {
        // 类别选择页面
        uni.navigateTo({
          url,
          events: {
            searchInfo: categoryList => {
              this.params.categoryList = categoryList;
              this.searchData();
            }
          }
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import './salePage.scss';

.procurement {
  box-sizing: border-box;
  .icon_box {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    padding: 15rem 20rem 0 20rem;
    box-sizing: border-box;
  }

  .icon_view {
    width: 20%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin-bottom: 13rem;

    .text {
      text-align: center;
      width: 100%;
      height: 12rem;
      line-height: 12rem;
      font-size: 12rem;
      color: rgba(128, 128, 128, 1);
      margin-top: 9rem;
    }
  }

  .icons {
    width: 29rem;
    height: 29rem;
  }

  .header_select {
    width: 100rem;
  }

  .left_radius,
  .right_radius {
    padding: 0 10rem;
    font-size: 14rem;
    height: 36rem;
    line-height: 36rem;
    width: 50%;
    text-align: center;
    color: #fff;
    font-size: 14rem;
    font-weight: 700;
  }

  .left_radius {
    border-radius: 20rem 0rem 0rem 20rem;
    background: #ff8d1a;

    image {
      margin-right: 7rem;
    }
  }

  .right_radius {
    background-color: #2a82e4;
    border-radius: 0rem 20rem 20rem 0rem;

    image {
      margin-left: 7rem;
    }
  }

  .suspend_box {
    position: fixed;
    bottom: 10rem;
    width: 100%;
    box-sizing: border-box;
  }

  .call_phone {
    color: #ff7c00;
    border-radius: 50rem;
    font-size: 12rem;
    padding: 0 10rem;
    height: 26rem;
    line-height: 26rem;
    background-color: #fcead7;
    margin-left: 14rem;
  }

  .normal_twelve_txt {
    font-size: 12rem;
  }

  .orange_color {
    color: #ffc300;
    margin: 0 2rem 0 4rem;
  }

  .small_solid_arrow {
    width: 8rem;
    height: 8rem;
  }
}
</style>
